package com.example.wiki.service;


import com.example.wiki.auth.exception.BusinessException;
import com.example.wiki.auth.exception.BusinessExceptionCode;
import com.example.wiki.domain.Content;
import com.example.wiki.domain.Doc;
import com.example.wiki.domain.DocExample;

import com.example.wiki.mapper.ContentMapper;
import com.example.wiki.mapper.DocMapper;
import com.example.wiki.mapper.DocMapperCust;
import com.example.wiki.req.DocQueryReq;
import com.example.wiki.req.DocSaveReq;
import com.example.wiki.resp.DocQueryResp;
import com.example.wiki.resp.PageResp;
import com.example.wiki.utils.CopyUtil;
import com.example.wiki.utils.RedisUtil;
import com.example.wiki.utils.RequestContext;
import com.example.wiki.utils.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.List;


@Service
public class DocService {
    private static final Logger Log = LoggerFactory.getLogger(DocService.class);
    @Resource
    private DocMapper docMapper;
    @Resource
    private ContentMapper contentMapper;

    @Resource
    private DocMapperCust docMapperCust;


    @Resource
    private RedisUtil redisUtil;
    @Resource
    private SnowFlake snowFlake;



    public List<DocQueryResp> all(Long ebookId) {
        DocExample docExample = new DocExample();

        if(ebookId!=null){
            docExample.createCriteria().andEbookIdEqualTo(ebookId);
            docExample.setOrderByClause("sort asc");
        }else {

            DocExample.Criteria criteria = docExample.createCriteria();
        }
        List<Doc> docList = docMapper.selectByExample(docExample);
        //列表复制
        List<DocQueryResp> respList = CopyUtil.copyList(docList, DocQueryResp.class);

        return respList;
    }





    /**
     * 查询列表
     * @param req
     * @return
     */
    public PageResp<DocQueryResp> list(DocQueryReq req) {
        System.out.println("req"+req);


        DocExample docExample = new DocExample();
        DocExample.Criteria criteria = docExample.createCriteria();


        PageHelper.startPage(req.getPage(),req.getSize());
        List<Doc> docList = docMapper.selectByExample(docExample);

        PageInfo<Doc> pageInfo = new PageInfo<>(docList);
        Log.info("总行数"+pageInfo.getTotal());
        Log.info("总页数"+pageInfo.getPages());

//        List<DocResp> respList  =new ArrayList<>();
//        for (Doc doc :docList){
//
//            DocResp docResp = new DocResp();
//            //最原始的设置属性值方法
////            docResp.setName(doc.getName());
////            利用beanutil的简便方法
////            BeanUtils.copyProperties(doc,docResp);
////            respList.add(docResp);
//        }
        //利用工具封装，简化上面代码

        List<DocQueryResp> respList = CopyUtil.copyList(docList, DocQueryResp.class);
        PageResp<DocQueryResp> pageResp =new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(respList);
        return pageResp;
    }


        /**
         * 保存
         */
        public void save(@RequestBody DocSaveReq req) {
//            System.out.println(req);
            Doc doc = CopyUtil.copy(req, Doc.class);
            Content content = CopyUtil.copy(req,Content.class);

            if (ObjectUtils.isEmpty(req.getId())) {
                // 新增  自增 uuid 雪花
                doc.setId(snowFlake.nextId());
                doc.setViewCount(0);
                doc.setVoteCount(0);
                docMapper.insert(doc);


                content.setId(doc.getId());
                contentMapper.insert(content);
            } else {
                // 更新
                docMapper.updateByPrimaryKey(doc);
               int count= contentMapper.updateByPrimaryKeyWithBLOBs(content);
               if(count ==0){
                   contentMapper.insert(content);
               }
            }
        }

        public void delete(Long id){
            docMapper.deleteByPrimaryKey(id);
        }
        public void delete(List<Long> ids) {
            DocExample docExample = new DocExample();
            DocExample.Criteria criteria = docExample.createCriteria();
            criteria.andIdIn(ids);
            docMapper.deleteByExample(docExample);
    }

    public String findContent(Long id) {
        Content content = contentMapper.selectByPrimaryKey(id);

        //文档阅读树+1
        docMapperCust.increateViewCount(id);

        if (ObjectUtils.isEmpty(content)) {
            return "";
        } else {
            return content.getContent();
        }

    }
    /**
     * 点赞
     */
    public void vote(Long id) {
         docMapperCust.increaseVoteCount(id);
//         远程IP+doc.id作为key，24小时内不能重复
        String ip = RequestContext.getRemoteAddr();
        if (redisUtil.validateRepeat("DOC_VOTE_" + id + "_" + ip, 5000)) {
            docMapperCust.increaseVoteCount(id);
        } else {
            throw new BusinessException(BusinessExceptionCode.VOTE_REPEAT,403);
        }
//
//        // 推送消息
//        Doc docDb = docMapper.selectByPrimaryKey(id);
//        String logId = MDC.get("LOG_ID");
//        wsService.sendInfo("【" + docDb.getName() + "】被点赞！", logId);
//        // rocketMQTemplate.convertAndSend("VOTE_TOPIC", "【" + docDb.getName() + "】被点赞！");

    }
    public void updateEbookInfo() {
        docMapperCust.updateEbookInfo();
    }
}

